package com.mlethe.library.socialtool.core;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.alipay.share.sdk.openapi.APImageObject;
import com.alipay.share.sdk.openapi.APMediaMessage;
import com.alipay.share.sdk.openapi.APTextObject;
import com.alipay.share.sdk.openapi.APWebPageObject;
import com.alipay.share.sdk.openapi.BaseReq;
import com.alipay.share.sdk.openapi.BaseResp;
import com.alipay.share.sdk.openapi.IAPAPIEventHandler;
import com.alipay.share.sdk.openapi.SendMessageToZFB;
import com.mlethe.library.socialtool.callback.ShareActionListener;
import com.mlethe.library.socialtool.entity.Share;
import com.mlethe.library.socialtool.entity.ShareImage;
import com.mlethe.library.socialtool.entity.ShareText;
import com.mlethe.library.socialtool.entity.ShareWeb;

/**
 * 支付宝分享工具类
 * @author Mlethe
 */
public class AlipayShare {

    private final static EventHandler mEventHandler = new EventHandler();

    private static ShareActionListener mListener;

    public static void setShareActionListener(ShareActionListener listener) {
        mListener = listener;
    }

    public static ShareActionListener getShareActionListener() {
        return mListener;
    }

    /**
     * 分享结果处理
     *
     * @param intent
     * @return
     */
    public static boolean handleIntent(Alipay alipay, Intent intent, IAPAPIEventHandler handler) {
        if (alipay == null) {
            return false;
        }
        try {
            return alipay.getApi().handleIntent(intent, handler);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 分享结果处理(推荐)
     * @param alipay
     * @param intent
     * @return
     */
    public static boolean handleIntent(Alipay alipay, Intent intent) {
        return handleIntent(alipay, intent, mEventHandler);
    }

    /**
     * 分享文本
     *
     * @param share        分享的文本
     */
    public static void share(Alipay alipay, ShareText share) {
        if (!alipay.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.ALIPAY);
                mListener = null;
            }
            return;
        }
        // 初始化一个APTextObject对象
        APTextObject textObject = new APTextObject();
        textObject.text = share.getTitle();
        // 用APTextObject对象初始化一个APMediaMessage对象
        APMediaMessage mediaMessage = new APMediaMessage();
        mediaMessage.mediaObject = textObject;
        // 构造一个Req
        SendMessageToZFB.Req req = new SendMessageToZFB.Req();
        req.message = mediaMessage;
        req.transaction = Util.buildTransaction(share.getTransaction());
        // 调用api接口发送消息到支付宝
        alipay.getApi().sendReq(req);
    }

    /**
     * 分享图片
     *
     * @param flag (0：分享到好友,1：分享到生活圈)
     * @param share
     */
    public static void share(Context context, Alipay alipay, int flag, ShareImage share) {
        if (!alipay.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.ALIPAY);
                mListener = null;
            }
            return;
        }
        APImageObject imageObject = new APImageObject();
        if (share.getImagePath() != null && !"".equals(share.getImagePath())) {
            imageObject.imagePath = share.getImagePath();
        } else if (share.getImageData() != null) {
            imageObject.imageData = share.getImageData();
        } else if (share.getImageUrl() != null && !"".equals(share.getImageUrl())) {
            imageObject.imageUrl = share.getImageUrl();
        } else if (share.getBitmap() != null) {
            Bitmap bitmap = share.getBitmap();
            imageObject = new APImageObject(bitmap);
            if (bitmap != null) {
                bitmap.recycle();
            }
        } else if (share.getDrawableId() != 0) {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), share.getDrawableId());
            imageObject = new APImageObject(bitmap);
            if (bitmap != null) {
                bitmap.recycle();
            }
        }
        APMediaMessage mediaMessage = new APMediaMessage();
        mediaMessage.mediaObject = imageObject;
        SendMessageToZFB.Req req = new SendMessageToZFB.Req();
        req.message = mediaMessage;
        req.transaction = Util.buildTransaction(share.getTransaction());
        //在支付宝版本会合并分享渠道的情况下,不需要传递分享场景参数
        if (!alipay.isAlipayIgnoreChannel()) {
            if (flag == Share.FLAG_FRIEND) {
                req.scene = SendMessageToZFB.Req.ZFBSceneSession;
            } else if (flag == Share.FLAG_MOMENTS) {
                req.scene = SendMessageToZFB.Req.ZFBSceneTimeLine;
            }
        }
        alipay.getApi().sendReq(req);
    }

    /**
     * 分享网页
     *
     * @param flag (0：分享到好友,1：分享到生活圈)
     * @param share
     */
    public static void share(Context context, Alipay alipay, int flag, ShareWeb share) {
        if (!alipay.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.ALIPAY);
                mListener = null;
            }
            return;
        }
        APWebPageObject webPageObject = new APWebPageObject();
        webPageObject.webpageUrl = share.getUrl();
        APMediaMessage webMessage = new APMediaMessage();
        webMessage.title = share.getTitle();
        webMessage.description = share.getDesc();
        webMessage.mediaObject = webPageObject;
        if (share.getImageUrl() != null && !"".equals(share.getImageUrl())) {
            webMessage.thumbUrl = share.getImageUrl();
        } else if (share.getImageData() != null) {
            webMessage.thumbData = share.getImageData();
        } else if (share.getBitmap() != null) {
            Bitmap thumbBmp = Util.bitmapFormat(share.getBitmap());
            webMessage.setThumbImage(thumbBmp);
            thumbBmp.recycle();
        } else if (share.getDrawableId() != 0) {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), share.getDrawableId());
            Bitmap thumbBmp = Util.bitmapFormat(bitmap);
            webMessage.setThumbImage(thumbBmp);
            thumbBmp.recycle();
        } else if (share.getImagePath() != null && !"".equals(share.getImagePath())) {
            Bitmap bitmap = BitmapFactory.decodeFile(share.getImagePath());
            Bitmap thumbBmp = Util.bitmapFormat(bitmap);
            webMessage.setThumbImage(thumbBmp);
            thumbBmp.recycle();
        }
        SendMessageToZFB.Req req = new SendMessageToZFB.Req();
        req.message = webMessage;
        req.transaction = Util.buildTransaction(share.getTransaction());
        //在支付宝版本会合并分享渠道的情况下,不需要传递分享场景参数
        if (!alipay.isAlipayIgnoreChannel()) {
            if (flag == Share.FLAG_FRIEND) {
                req.scene = SendMessageToZFB.Req.ZFBSceneSession;
            } else if (flag == Share.FLAG_MOMENTS) {
                req.scene = SendMessageToZFB.Req.ZFBSceneTimeLine;
            }
        }
        alipay.getApi().sendReq(req);
    }

    /**
     * 回调处理类
     */
    private static class EventHandler implements IAPAPIEventHandler {

        @Override
        public void onReq(BaseReq baseReq) {

        }

        @Override
        public void onResp(BaseResp baseResp) {
            handleResult(baseResp);
        }
    }

    /**
     * 处理分享回调
     * @param baseResp
     */
    public static void handleResult(BaseResp baseResp) {
        try {
            int errCode = baseResp.errCode;
            if (mListener == null) {
                return;
            }
            if (errCode == BaseResp.ErrCode.ERR_OK) {
                // 发送成功
                mListener.onComplete(Platform.ALIPAY);
            } else if (errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
                // 发送取消
                mListener.onCancel(Platform.ALIPAY);
            } else if (errCode == BaseResp.ErrCode.ERR_AUTH_DENIED) {
                // 权限验证失败
                mListener.onFail(Platform.ALIPAY);
            } else if (errCode == BaseResp.ErrCode.ERR_SENT_FAILED) {
                // 发送失败
                mListener.onFail(Platform.ALIPAY);
            } else {
                // 未知错误
                mListener.onFail(Platform.ALIPAY);
            }
            mListener = null;
        } catch (Exception e) {
            mListener = null;
            e.printStackTrace();
        }
    }

}
